package cn.b.sky.i18n.listener;

import cn.b.sky.i18n.enums.LocaleResourceEnum;
import cn.b.sky.i18n.model.LocaleResourceInfo;
import cn.b.sky.i18n.model.SystemLanguageInfo;
import cn.b.sky.i18n.service.I18nService;
import cn.b.sky.i18n.utils.LocaleResourceBundle;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.util.List;

/**
 * 
 * <strong>Title : I18nResourceListener.java<br></strong>
 * <strong>Package : cn.b.sky.i18n.listener<br></strong>
 * <strong>Description : </strong>容器启动加载国际化资源<br> 
 * <strong>Create on : 2016-5-11 下午1:19:39<br></strong>
 * <p>
 * @author lidapeng<br>
 * @version <strong>v1.0.0</strong><br>
 * <br>
 * <strong>修改历史:</strong><br>
 * 修改人|修改日期|修改描述<br>
 * -------------------------------------------<br>
 * <br>
 * <br>
 */
public class I18nResourceListener implements ServletContextListener {

  @Override
  public void contextDestroyed(ServletContextEvent arg0) {
    // do something

  }

  @Override
  public void contextInitialized(ServletContextEvent sce) {
    // 得到Bean工厂
    I18nService i18nService = (I18nService) WebApplicationContextUtils
        .getWebApplicationContext(sce.getServletContext()).getBean("i18nService");  
    
    List<SystemLanguageInfo> languages = i18nService.listLanguage();
    //一个LocaleResourceEnum就是一个Bundle
    for (SystemLanguageInfo language : languages) {
      for (LocaleResourceEnum lresource : LocaleResourceEnum.values()) {
        String resourceSet = lresource.getValue();
        String languageCode = language.getLanguageCode();
               
        List<LocaleResourceInfo> resourceList = i18nService.listLocaleResource(resourceSet, languageCode);
        //循环国际化资源，放入每个bundle的resources里
        for (LocaleResourceInfo localeResource : resourceList) {   
          //设置setBundle
          LocaleResourceBundle.setBundle(localeResource.getSiteCode(), resourceSet, languageCode);
          //设置resources
          LocaleResourceBundle.getBundle(localeResource.getSiteCode(), resourceSet, languageCode).getResources().put(localeResource.getResourceKey(), localeResource.getResourceValue());
          //设置开启国际化标签
          LocaleResourceBundle.getBundle(localeResource.getSiteCode(), resourceSet, languageCode);
        }
      }
    }
  }
}
